package com.luoqiu.yygh.gateway.filter;

import com.alibaba.fastjson.JSONObject;
import com.luoqiu.yygh.common.helper.JwtHelper;
import com.luoqiu.yygh.common.result.Result;
import com.luoqiu.yygh.common.result.ResultCodeEnum;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.List;

@Component
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    private final AntPathMatcher matcher = new AntPathMatcher();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();
        ServerHttpResponse response = exchange.getResponse();
        if (matcher.match("/*/inner/**", path)) {
            return out(response, ResultCodeEnum.PERMISSION);
        }
        Long userId = this.getUserId(request);
        if (StringUtils.isEmpty(userId)) {
            return out(response, ResultCodeEnum.LOGIN_AURH);
        }
        return chain.filter(exchange);
    }

    private Long getUserId(ServerHttpRequest request) {
        List<String> authToken = request.getHeaders().get("authToken");
        if (authToken == null) {
            return null;
        }
        String token = authToken.get(0);
        return JwtHelper.getUserId(token);
    }


    private Mono<Void> out(ServerHttpResponse response, ResultCodeEnum permission) {
        Result<Object> result = Result.build(null, permission);
        byte[] bytes = JSONObject.toJSONString(result).getBytes(StandardCharsets.UTF_8);
        DataBuffer wrap = response.bufferFactory().wrap(bytes);
        response.getHeaders().add("Content-type", "application/json;charset=utf-8");
        return response.writeWith(Mono.just(wrap));
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
